package com.easyExcel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.read.listener.ReadListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserListener implements ReadListener<User> {

    /***
     * 批量处理阈值
     */
    private static final int MAX_COUNT = 3000;

    /***
     * 批量处理集合
     */
    List<User> list = new ArrayList();

    @Override
    public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
        System.out.println("表头：" + headMap);
    }

    /***
     * 读取内容,每一条数据解析都会来调用
     */
    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        list.add(user);
        // 达到阈值后进行处理，防止几万条数据在内存，产生OOM
        if (list.size() >= MAX_COUNT){
            saveData(list);
            list.clear();
        }
    }

    /***
     * 读取完成
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData(list);
        list.clear();
        System.out.println("读取完成");
    }

    // 读取的数据处理
    public void saveData(List<User> list){
        for (User user : list) {
            System.err.println(user);
        }
    }

    @Override
    public void extra(CellExtra extra, AnalysisContext context) {
        
    }
}
